#include "UPopUpMenu.h"
#include "UGLFont.h"
#include "UWindowManager.h"

using namespace std;
using std::min;


void TPopUpMenu::EventHandle(SDL_Event event)
{
	switch (event.type)
	{
		case(SDL_MOUSEMOTION):
		{
			MouseMove(event.motion.x, event.motion.y, event.motion.state);
			break;
		}
		case(SDL_MOUSEBUTTONDOWN):
		{
			MouseDown(event.motion.x, event.motion.y, event.button.button);
			break;
		}
		case(SDL_MOUSEBUTTONUP):
		{
			MouseUp(event.motion.x, event.motion.y, event.button.button);
			break;
		}
	}
}

int TPopUpMenu::MouseIndex(int X, int Y)
{
	if ((X>Left && X<Left+MaxTextWidth) && (Y>Top && Y<Top+TotalStrHeight))
		return (int)((Y-Top)/GLFont->Height());

	return -1;
}

TPopUpMenu::TPopUpMenu()
{
	MaxTextWidth	= 0;
	TotalStrHeight	= 0;
	Enabled			= false;
}

void TPopUpMenu::PopUp(int X, int Y)
{
	Left	= min(X, ScreenWidth-MaxTextWidth-10);
	Top		= min(Y, ScreenHeight-TotalStrHeight-10);
	Enabled = true;
	WindowManager->PopUpMenu = this;
}

void TPopUpMenu::AddEntry(string Text, function<void()> Function)
{
	Entries.push_back(TPopUpMenuEntry(Text, Function));
	MaxTextWidth= max(MaxTextWidth,  GLFont->TextWidth(Text.c_str()));
	TotalStrHeight+= (int)GLFont->Height();
}

void TPopUpMenu:: Draw(int X, int Y, int mstate)
{

	glColor3f(0.9, 0.9, 0.9);
 	glBegin(GL_QUADS);
 		glVertex2i(Left					, Top);
 		glVertex2i(Left+MaxTextWidth+10	, Top);
 		glVertex2i(Left+MaxTextWidth+10	, Top+TotalStrHeight+5);
 		glVertex2i(Left					, Top+TotalStrHeight+5);
	glEnd();


	int mouseindex = MouseIndex(X, Y);

	if (mouseindex>-1)// mouse over the menu
	{
		glColor3f(0, 0 , 0.9);
 		glBegin(GL_QUADS);
 			glVertex2f(Left+1				, Top+2+mouseindex*GLFont->Height());
 			glVertex2f(Left+MaxTextWidth+9	, Top+2+mouseindex*GLFont->Height());
 			glVertex2f(Left+MaxTextWidth+9	, Top+3+(mouseindex+1)*GLFont->Height());
 			glVertex2f(Left+1				, Top+3+(mouseindex+1)*GLFont->Height());
		glEnd();

		glColor3f(0.8, 0.8 , 1);
 		glBegin(GL_QUADS);
 			glVertex2f(Left+2				, Top+3+mouseindex*GLFont->Height());
 			glVertex2f(Left+MaxTextWidth+8	, Top+3+mouseindex*GLFont->Height());
 			glVertex2f(Left+MaxTextWidth+8	, Top+2+(mouseindex+1)*GLFont->Height());
 			glVertex2f(Left+2				, Top+2+(mouseindex+1)*GLFont->Height());
		glEnd();
	}
	glColor3f(0, 0, 0);

	for (size_t i=0; i < Entries.size(); ++i)
	{
		GLFont->drawText(Left+5, Top+i*GLFont->Height(), Entries[i].Text.c_str());
	}
	glColor3f(1, 1, 1);
}

void TPopUpMenu:: MouseMove(int X, int Y, int mstate)
{

}

void TPopUpMenu:: MouseDown(int X, int Y, uint8 button)
{

}

void TPopUpMenu:: MouseUp(int X, int Y, uint8 button)
{
	if ( button == SDL_BUTTON_LEFT )
	{
		uint32 Index = MouseIndex(X, Y);
		if (Index>=0 && Index<=Entries.size())
		{
			Entries[Index].Function();

		}
	}
	Enabled = false;
}
